//
//  AppDelegate.m
//  Estate
//
//  Created by heyong on 16/5/25.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import <Bugly/Bugly.h>
#import "HZStatusBarEffect/HZStatureEffect.h"


@interface AppDelegate ()<BuglyDelegate>
{
    BMKMapManager *_mapManager;
}

@end

@implementation AppDelegate
- (TimeingSynchronization *)timeSnc{
    if(!_timeSnc){
        _timeSnc=[[TimeingSynchronization alloc]init];
    }
    return _timeSnc;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
    self.window.backgroundColor =[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    
    //删除过期图片
    [LSUtility deleteOutofdateImageFile];
    
    //判断是否登录
    if(DEF_PERSISTENT_GET_OBJECT(@"role")!=nil){
        
        /*
         *  判断版本是否更新
         */
        //版本
        NSString *key = (NSString *)kCFBundleVersionKey;
        //新版本号
        NSString *version = [NSBundle mainBundle].infoDictionary[key];
        //老版本号
        NSString *oldVersion =DEF_PERSISTENT_GET_OBJECT(@"firstLanch");
        //是否是首次使用APP、是否是首次使用APP
        BOOL is=![version isEqualToString:oldVersion]||DEF_PERSISTENT_GET_OBJECT(@"FirstLoad") == nil;
        
        NSString *ip= DEFIP;
        //是首次登录 老版本
        if (is) {
            if(!ip || [ip isEqualToString:@""]){
                IpDetailController *ipsetCtr=[[IpDetailController alloc]init];
                ipsetCtr.first=YES;
                self.window.rootViewController=ipsetCtr;
                
            }else
            {
                if(USERID&&PROID&&USERROLE){
                    self.tabBarController = [[EsTabBarController alloc] init];
                    [self.tabBarController setProId:DEF_PERSISTENT_GET_OBJECT(@"proid")
                                         setProType:DEF_PERSISTENT_GET_OBJECT(@"proType")
                                          andUserId:DEF_PERSISTENT_GET_OBJECT(@"userid")
                                            andRole:DEF_PERSISTENT_GET_OBJECT(@"role")];
                    self.window.rootViewController = self.tabBarController;
                }else{
                    LoginViewController *loginCtl=[[LoginViewController alloc]init];
                    self.window.rootViewController = loginCtl;
                }
            }
            //不是首次登录 新版本
        }else{
            if(!ip ||[ip isEqualToString:@""]){
                IpDetailController *ipsetCtr=[[IpDetailController alloc]init];
                ipsetCtr.first=YES;
                self.window.rootViewController=ipsetCtr;
                
            }else
            {
                self.tabBarController = [[EsTabBarController alloc] init];
                [self.tabBarController setProId:DEF_PERSISTENT_GET_OBJECT(@"proid")
                                     setProType:DEF_PERSISTENT_GET_OBJECT(@"proType")
                                      andUserId:DEF_PERSISTENT_GET_OBJECT(@"userid")
                                        andRole:DEF_PERSISTENT_GET_OBJECT(@"role")];
                
                self.window.rootViewController = self.tabBarController;
            }
        }
        //得到自动配置设置
        [self timeSetting];
    }else{
        //判断ip地址是否存在
        NSString *ip= DEFIP;
        
        if(!ip || [ip isEqualToString:@""]){
            IpDetailController *ipsetCtr=[[IpDetailController alloc]init];
            ipsetCtr.first=YES;
            self.window.rootViewController=ipsetCtr;
        }else
        {
            LoginViewController *loginCtl=[[LoginViewController alloc]init];
            self.window.rootViewController = loginCtl;
        }
    }
    //定时刷新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(timerRenovatingData:) name:@"reloadBtn" object:nil];
    
    // 刷新待处理事项
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadNotToDealWithData) name:@"home" object:nil];
    
    [self settingBaiDuMap];
    [self setBugly];
    [self registerNO];
    [self.window makeKeyAndVisible];
    
    return YES;
}

-(void)registerNO{
    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
        // iOS8以后 本地通知必须注册(获取权限)
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
}
//调用百度地图
- (void)settingBaiDuMap{
    //百度地图
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:DEF_BDMAP_API_AK  generalDelegate:nil];
    if (!ret) {
        DeLog(@"manager start failed!");
    }
}
//设置Bugly
-(void)setBugly{
    BuglyConfig * config = [[BuglyConfig alloc] init];
    //开启卡顿
    config.blockMonitorEnable = YES;
    //卡顿分析
    config.blockMonitorTimeout = 2;
    config.consolelogEnable = YES;
    config.delegate = self;
    // 设置自定义日志上报的级别，默认不上报自定义日志
    config.reportLogLevel = BuglyLogLevelWarn;
    [Bugly startWithAppId:@"771a4121e0" config:config];
}
- (NSString *)attachmentForException:(NSException *)exception {
    return @"Do you want to do...";
}
//得到服务器设置
-(void)timeSetting{
    /*
     * 得到设置 判断定时刷新是否开启
     */
    NSMutableDictionary *settingDic=DEF_PERSISTENT_GET_OBJECT(USERID);
    if(settingDic){
        NSLog(@"%@",settingDic);
        //得到本地存储的刷新频率设置
        //开启了定时器
        if([settingDic[@"isTiming"] isEqualToString:@"yes"]){
            NSInteger time=[settingDic[@"time"]integerValue];
            [self createTime:time];
            
        }else{
            [_refreshTimer invalidate];
            _refreshTimer = nil;
            //关闭定时器
            [_refreshTimer setFireDate:[NSDate distantFuture]];
        }
    }else{
        return;
    }
}

#pragma  mark -定时器刷新方法
- (void)createTime:(NSInteger )time{
    //然后创建定时器
    _refreshTimer =  [NSTimer scheduledTimerWithTimeInterval:(time*60) target:self.timeSnc selector:@selector(isSyncLocalData) userInfo:nil repeats:YES];
}

//个人设置页面 设置时的操作
- (void)timerRenovatingData:(NSNotification *)notifi{
    NSDictionary *dic=notifi.userInfo;
    NSString *isRefresh=dic[@"isTiming"];
    //开启刷新
    if([isRefresh isEqualToString:@"yes"]){
        NSInteger time=[dic[@"time"]integerValue];
        _refreshTimer =  [NSTimer scheduledTimerWithTimeInterval:(time*60)-5 target:self.timeSnc selector:@selector(isSyncLocalData) userInfo:nil repeats:YES];
    }else{
        //关闭刷新
        [_refreshTimer invalidate];
        //关闭定时器
        [_refreshTimer setFireDate:[NSDate distantFuture]];
        _refreshTimer = nil;
        
    }
}

#pragma  mark - 刷新数据（待办事件等一系列操作）
- (void)reloadNotToDealWithData {
    // 获取当前角色
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    
    // 工作数量
    NSArray *workArr = [NSArray array];
    // 待办数量
    NSArray *gtasksArr = [NSArray array];
    // 总监
    if ([role isEqualToString:@"USER_01"]) {
        workArr = [self getZJWork];
        gtasksArr = [self getZJgtasks];
        
        // 监理
    } else if ([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]) {
        workArr = [self getJLWork];
        gtasksArr = [self getJLgtasks];
    }
    
    EsTabBarController *tabBarController = (EsTabBarController *)self.window.rootViewController;
    
    NSArray *tabBarItems = tabBarController.tabBar.items;
    
    // 工作Item
    UITabBarItem *workTabBarItem = [tabBarItems objectAtIndex:1];
    // 待办Item
    UITabBarItem *gtasksTabBarItem = [tabBarItems objectAtIndex:2];
    
    // 刷新工作
    if (workArr.count > 0) {
        
        workTabBarItem.badgeValue = [NSString stringWithFormat:@"%d", workArr.count];
        
    } else {
        workTabBarItem.badgeValue = nil;
    }
    
    // 刷新待办
    if (gtasksArr.count > 0) {
        gtasksTabBarItem.badgeValue = [NSString stringWithFormat:@"%d", gtasksArr.count];
        
    } else {
        gtasksTabBarItem.badgeValue = nil;
    }
}

// 获取待处理事项(总监工作)
- (NSArray *)getZJWork {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSMutableArray *WorkArrZJ = [NSMutableArray array];
    // 日记
    NSString *sqlRJ=[NSString stringWithFormat:@"select *, substr(DIARY_TIME,1,10) AS Day from WORK_DIARY WHERE PRO_ID = '%@' AND DIARY_USER != '%@' AND REVIEW_USER = '%@' AND REVIEW_STATE = '0' ORDER BY DIARY_TIME desc", PROID, USERID, USERID];
    FMResultSet *resultRJ = [db executeQuery:sqlRJ];
    
    while ([resultRJ next]) {
        //id
        NSString *ids=[resultRJ stringForColumn:@"ID"];
        
        if (ids && ![ids isEqualToString:@""]) {
            //添加到数组
            [WorkArrZJ addObject:ids];
        }
    }
    
    // 日志
    NSString *sqlRZ=[NSString stringWithFormat:@"SELECT substr(CREATE_TIME,1,10) AS Day,* FROM WORK_LOG WHERE PRO_ID = '%@' AND LOG_USERS != '%@' AND REVIEW_STATE = '0' ORDER BY CREATE_TIME desc ", PROID, USERID];
    
    FMResultSet *resultRZ = [db executeQuery:sqlRZ];
    while ([resultRZ next]) {
        //id
        NSString *ids=[resultRZ stringForColumn:@"ID"];
        
        if (ids && ![ids isEqualToString:@""]) {
            //添加到数组
            [WorkArrZJ addObject:ids];
        }
    }
    [db close];
    return WorkArrZJ;
}

// 获取待处理数量(总监待办)
- (NSArray *)getZJgtasks {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSMutableArray *gtasksArrZJ = [NSMutableArray array];
    
    // 获取跟进
    NSString *sqlGJ = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE PRO_ID = '%@' AND PROCESS_STAGE IN(%d, %d) AND PROCESS_TYPE = '2' ORDER BY CREATE_TIME DESC", PROID,PROCESS_STAGE_REVIEW,PROCESS_STAGE_CHECK_PASS_YES];
    FMResultSet *resultGJ = [db executeQuery:sqlGJ];
    
    // 遍历结果
    while ([resultGJ next]) {
        NSString *ID = [resultGJ stringForColumn:@"ID"];
        if (ID && ![ID isEqualToString:@""]) {
            //添加到数组
            [gtasksArrZJ addObject:ID];
        }
    }
    
    // 获取督办(无的发送形式)
    NSString *sqlDB2 = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE PRO_ID = '%@'  AND PROCESS_STAGE IN(%d,%d) AND PROCESS_TYPE = '1' ORDER BY CREATE_TIME DESC", PROID,PROCESS_STAGE_REVIEW,PROCESS_STAGE_CHECK_PASS_YES];
    FMResultSet *resultDB2 = [db executeQuery:sqlDB2];
    // 遍历结果
    while ([resultDB2 next]) {
        NSString *ID = [resultDB2 stringForColumn:@"ID"];
        if (ID && ![ID isEqualToString:@""]) {
            //添加到数组
            [gtasksArrZJ addObject:ID];
        }
    }
    
    // 获取巡检
    NSString *sqlXJ = [NSString stringWithFormat:@"SELECT *, substr(INSPECT_START_TIME, 1, 4) as YEAR, substr(INSPECT_START_TIME, 6, 2) as MONTH, substr(INSPECT_START_TIME, 9, 2) as DAY FROM INSPECT_PROCESS WHERE PRO_ID = '%@' AND INSPECT_STATE = '3' ORDER BY INSPECT_START_TIME DESC", PROID];
    FMResultSet *resultXJ = [db executeQuery:sqlXJ];
    
    while ([resultXJ next]) {
        // 巡检流程ID
        NSString *inspectProcessID = [resultXJ stringForColumn:@"ID"];
        if (inspectProcessID && ![inspectProcessID isEqualToString:@""]) {
            //添加到数组
            [gtasksArrZJ addObject:inspectProcessID];
        }
    }
    [db close];
    return gtasksArrZJ;
}

// 获取待处理事项(监理工作)
- (NSArray *)getJLWork {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSMutableArray *WorkArrJL = [NSMutableArray array];
   
    [db close];
    return WorkArrJL;
}

// 获取待处理事项(监理待办)
- (NSArray *)getJLgtasks {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSMutableArray *gtasksArrJL = [NSMutableArray array];
    // 获取跟进 待复查 审阅不通过
    NSString *sqlGJ = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE PRO_ID = '%@' and ((PROCESS_PUBLISHERS='%@' AND PROCESS_STAGE IN(%d)) OR (PROCESS_RECIFY_USERS='%@' AND PROCESS_STAGE IN(%d))) AND PROCESS_TYPE = '2'  ORDER BY CREATE_TIME DESC", PROID,USERID,PROCESS_STAGE_CHECK,USERID,PROCESS_STAGE_DOING];
 
    [self addData:sqlGJ fromDB:db array:gtasksArrJL];
    
    //    PROCESS_PUBLISHERS 发起人
    //    PROCESS_MASTERS 负责人
    //    PROCESS_RECIFY_USERS 整改人

    //获取督办
    // 获取督办
    NSString *sqlDB = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE PRO_ID = '%@' AND ((PROCESS_MASTERS = '%@' AND PROCESS_STAGE IN(%d,%d)) OR (PROCESS_RECIFY_USERS = '%@' AND PROCESS_STAGE IN(%d))) AND PROCESS_TYPE = '1' ORDER BY CREATE_TIME DESC", PROID,USERID,PROCESS_STAGE_REVIEW_PASS_NO,PROCESS_STAGE_CHECK,USERID,PROCESS_STAGE_DOING];

    [self addData:sqlDB fromDB:db array:gtasksArrJL];
    
    // 获取验收
    NSString *sqlYS = [NSString stringWithFormat:@"SELECT *,time(CREATE_TIME) FROM PROCESS WHERE PRO_ID = '%@' AND PROCESS_MASTERS = '%@' AND ID IN(SELECT PROCESS_ID FROM PROCESS_RECORD) AND PROCESS_STAGE IN(1, 4,402) AND PROCESS_TYPE = '3' ORDER BY CREATE_TIME DESC", PROID, USERID];
    [self addData:sqlYS fromDB:db array:gtasksArrJL];

   
    
    // 获取验收
//    NSString *sqlYS = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE PRO_ID = '%@' AND PROCESS_MASTERS = '%@' AND PROCESS_STAGE IN(1, 4,401) AND PROCESS_TYPE = '3' ORDER BY CREATE_TIME DESC", PROID, USERID];
//
//    FMResultSet *resultYS = [db executeQuery:sqlYS];
//    // 遍历结果
//    while ([resultYS next]) {
//
//        NSString *ID = [resultYS stringForColumn:@"ID"];
//
//        if (ID && ![ID isEqualToString:@""]) {
//            //添加到数组
//            [WorkArrJL addObject:ID];
//        }
//    }
    
    
    [db close];
    return gtasksArrJL;
}

-(void)addData:(NSString *)sqlGJ fromDB:(FMDatabase *)db array:(NSMutableArray *)array
{
    FMResultSet *resultGJ = [db executeQuery:sqlGJ];
    // 遍历结果
    while ([resultGJ next]) {
        NSString *ID = [resultGJ stringForColumn:@"ID"];

        if (ID && ![ID isEqualToString:@""]) {
            //添加到数组
            [array addObject:ID];
        }
    }
}
//禁止屏幕旋转
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    //删除过期图片
    [LSUtility deleteOutofdateImageFile];
    //发送首页通知
    [[NSNotificationCenter defaultCenter]postNotificationName:@"indexView" object:nil];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
// 本地通知回调函数，当应用程序在前台时调用
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSString *msg = notification.userInfo[@"name"];
    if([msg isEqualToString:@"有您新内容，待更新！"]){
        [HZStatureEffect showMessage:@"有您新内容，待更新！"];
    }else{
        UIAlertView *Alert = [[UIAlertView alloc]initWithTitle:@"提醒" message:msg delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [Alert show];
        NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
        badge -= notification.applicationIconBadgeNumber;
        badge = badge >= 0 ? badge : 0;
        [UIApplication sharedApplication].applicationIconBadgeNumber = badge;
    }
  
}
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
